import { Component, ViewChild } from '@angular/core';
import { STComponent, STColumn } from '@delon/abc/st';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api';
import { FileService } from 'src/app/shared/fileService';
import { ResponseCode } from 'src/app/shared/response.code';
import { TeamFolderComponent } from './team-folder.component';
import { TeamUploadComponent } from './team-upload.component';

@Component({
  selector: 'app-team',
  templateUrl: './team.component.html',
})
export class TeamComponent{
  page:any={show:false};
  // TODO 当前版本未实现批量操作
  showFileControl:any={group:false,rename:false,download:false,prview:false,edit:false};
  data: any[]=[];
  team: any[]=[];
  currentTeam: string="";
  currentTeamName: string='根目录';
  nodeLevel: any[] = [];
  fileType={
    folder:'folder',
    excel:'file-excel',
    word:'file-word',
    ppt:'file-ppt',
    pdf:'file-pdf',
    image:'file-image',
    gif:'file-gif',
    video:'video-camera',
    sound:'sound',
    text:'file-text',
    zip:'file-zip',
    unknown:'file-unknown'
  }
  constructor(private http: _HttpClient,private modal: ModalHelper,
    private fileService: FileService, private msg: NzMessageService) {}

  ngOnInit() {
    this.getMyTeam();    
  }

  @ViewChild('st', { static: false }) private st: STComponent;
  columns: STColumn[] = [
    // { index: 'id.value', type: 'checkbox' },
    { render: 'type', width:50 },
    { title: '文件名', render: 'name', sort: true},
    {
      width: 200,
      buttons: [
        {
          icon: 'download',
          iif: (record)=>this.canDownload(record),
          click: record => this.download(record),
        },
        {
          icon: 'eye',
          iif:(record)=>this.canPreview(record),
          click: record => this.preview(record),
        },
        {
          icon: 'delete',
          type:'del',
          iif:(record)=>this.canEdit(record),
          click: record => this.delete(record),
        },
      ],
    },
    { title: '大小', render: 'size' ,width: 150, sort: true},
    { title: '上传者', index: 'creator' ,width: 150, sort: true},
  ];

  teamColumns: STColumn[] = [ 
    { index: 'id', type: 'radio', width: 30 },
    { title: '组名称', index: 'name' }
  ]

  getMyTeam(){
    let that = this;
    this.http.get(Api.BaseUserApi+'/group')
      .subscribe(res=>{
        if(res.code===ResponseCode.SUCCESS){
          this.team = res.data;
          if(this.team&&this.team.length>0){
            this.currentTeam = this.team[0].id;
            this.currentTeamName = this.team[0].name;
            this.team[0].checked = true;
            this.getUserNode('0');
          }
        }else{
          that.msg.error(res.message?res.message:"获取用户组失败");
        }
      });
  }

  teamChange(event){
    console.log(event);
    if(event){
      if(event.type==='radio'){
        this.currentTeam = event.radio.id;
        this.currentTeamName = event.radio.name;
        this.getUserNode('0');
      }
    }
  }

  getUserNode(parentId){
    let that = this;
    let params = {parentId:parentId};
    this.http.get(Api.BaseNodeApi+'/' + this.currentTeam + '/node',params)
      .subscribe(res=>{
        if(res.code===ResponseCode.SUCCESS){
          this.data = res.data;
        }else{
          that.msg.error(res.message?res.message:"获取用户文件失败");
        }
      });
  }

  canDownload(record):boolean{
    // TODO 判断下载权限
    return true;
  }

  canPreview(record):boolean{
    // TODO 判断预览权限
    if(record.type==='folder'){
      return false;
    }
    return true;
  }

  canEdit(record):boolean{
    // TODO 判断编辑权限
    return true;
  }

  getFileType(type):string{
    const icon = this.fileType[type];
    return icon?icon:this.fileType.unknown;
  }

  getFileSize(type,size):string{
    if(type==='folder')
      return '-';
    if(size){
      if(size>1024*1024*1024*1024){
        return (size/1024/1024/1024/1024).toFixed(2) +'TB';
      }else if(size>1024*1024*1024){
        return (size/1024/1024/1024).toFixed(2) +'GB';
      } else if(size>1024*1024){
        return (size/1024/1024).toFixed(2) +'MB';
      } else if(size>1024){
        return (size/1024).toFixed(2) +'KB';
      }else {
        return size+'B';
      }
    }   
  }

  rowChange(event){
    if(event&&event.type==='checkbox'){
      if(event.checkbox&&event.checkbox.length>0){
        this.showFileControl.group=true;
        if(event.checkbox.length>1){
          this.showFileControl.rename=true;
        }else{
          this.showFileControl.rename=false;
          if(event.checkbox[0].type==='folder'){
            this.showFileControl.preview = true;
          }else{
            this.showFileControl.preview = false;
          }
          this.showFileControl.download = false;
          this.showFileControl.edit = false;
        }
      }else{
        this.showFileControl.group=false;
        this.showFileControl.rename=false;
      }
    }
    if(event&&event.type==='sort'){
      console.log('按照'+event.sort.column.indexKey+'进行'+event.sort.value+'排序');
    }
    console.log(event);
  }  

  intoNode(record) {
    console.log(record);
    if(record.type==='folder'){
      let exit = this.nodeLevel.filter(item=>item.id===record.id)
      if(exit.length){
        let tmp = [];
        for(let i = 0;i<this.nodeLevel.length;i++){
          tmp.push(this.nodeLevel[i]);
          if(this.nodeLevel[i].id===record.id)
            break;
        }
        this.nodeLevel = tmp;
      }else{
        this.nodeLevel.push(record);
      }
      this.getUserNode(record.id);
    }else{
      this.msg.info('点中了文件哦');
    }
  }
  
  prevFolder(){
    if(this.nodeLevel.length==1){
      this.getUserNode('0');
      this.nodeLevel = [];
      return;
    }
    this.intoNode(this.nodeLevel[this.nodeLevel.length-2]);
  }

  addFolder(){
    let parentId='0';
    if(this.nodeLevel.length){
      parentId=this.nodeLevel[this.nodeLevel.length-1].id;
    }
    this.modal
      .createStatic(TeamFolderComponent,{parentId:parentId,currentTeam:this.currentTeam})
      .subscribe(
        () => {
          if(this.nodeLevel.length>0){
            this.getUserNode(this.nodeLevel[this.nodeLevel.length-1].id);
          }else{
            this.getUserNode('0');
          }
        }
      );
  }

  uploadFile(){
    let parentId='0';
    if(this.nodeLevel.length){
      parentId=this.nodeLevel[this.nodeLevel.length-1].id;
    }
    this.modal
    .createStatic(TeamUploadComponent,{parentId:parentId,currentTeam:this.currentTeam})
    .subscribe( 
      () => {
        if(this.nodeLevel.length>0){
          this.getUserNode(this.nodeLevel[this.nodeLevel.length-1].id);
        }else{
          this.getUserNode('0');
        }
      }
    );
  }

  preview(record){
    this.msg.warning('请对接预览服务');
  }

  download(record){
    let that = this;
    let params = {id:record.id}
    this.fileService
    .download(Api.BaseNodeApi+'/download?id='+record.id)
    .subscribe(blob => {
      const a = document.createElement('a')
      const objectUrl = URL.createObjectURL(blob)
      a.href = objectUrl
      a.download = record.type==='folder'?record.name+'.zip':record.name;
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }

  delete(record){
    let that = this;
    let params = {id:record.id}
    if(record.type==='folder'){
      this.http.delete(Api.BaseNodeApi+'/folder',params)
      .subscribe(res=>{
        if(res.code===ResponseCode.SUCCESS){
          this.msg.success('删除成功');
          if(this.nodeLevel.length>0){
            this.getUserNode(this.nodeLevel[this.nodeLevel.length-1].id);
          }else{
            this.getUserNode('0');
          }
        }else{
          that.msg.error(res.message?res.message:"删除失败！");
        }
      });
    }else{
      this.http.delete(Api.BaseNodeApi,params)
      .subscribe(res=>{
        if(res.code===ResponseCode.SUCCESS){
          this.msg.success('删除成功');
          if(this.nodeLevel.length>0){
            this.getUserNode(this.nodeLevel[this.nodeLevel.length-1].id);
          }else{
            this.getUserNode('0');
          }
        }else{
          that.msg.error(res.message?res.message:"删除失败！");
        }
      });
    }
  }

  // TODO 以下功能此版本咱不实现
  rename(){
    this.msg.info('开发中');
  }

  copy(){
    this.msg.info('开发中');
  }

  move(){
    this.msg.info('开发中');
  }

  change(){
    this.msg.info('开发中');
  }
}